import { observable, action, toJS } from 'mobx';
import BaseFormStore from './BaseFormStore';
import { message, Modal } from 'antd';
import { CrmContactStore } from './crmContactStore';
import { WeaTools } from 'ecCom';
import * as Apis from '../apis/sellChance';
import * as Apis_Contact from '../apis/contact';

const weaComTypes = WeaTools.types;
import { WeaLocaleProvider } from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

export class FormStore extends BaseFormStore {
    @observable operation = '';
    @observable customerId = '';
    @observable sellChanceId = '';
    @observable crmContactStore = new CrmContactStore();
    @observable remindInfo = {};
    @observable loading = true;
    @observable msgcode = '';
    pathLocation = ''

    constructor() {
      super();
      this.viewTop = false;
    }

    initData() {
      this.parentStore = this.componentProps.parentStore;
      this.customerId = this.componentProps.params.customerid;
      this.sellChanceId = this.componentProps.params.sellChanceId;
      if (this.sellChanceId) {
        this.componentProps.params.operation = 'edit';
      } else {
        if (!this.parentStore) {
          // 新窗口方式新建显示头部
          this.viewTop = true;
        }
        this.componentProps.params.operation = 'add';
      }
    }
    getFormData(componentInitCallBack) {
      // const requestParams = this.componentProps.params;
      let requestParams = this.componentProps.params;
      if (this.componentProps.params.operation != 'add') {
        requestParams = Object.assign({}, this.componentProps.tabStore.pathLocation, this.componentProps.params);
        delete requestParams.sellchanceId;// 重复删除
      }

      Apis.getChanceForm(requestParams).then((data) => {
        componentInitCallBack(data);
      });
    }

    @action
    doSaveData(requestParams, doSaveCallBack) {
      const that = this;
      this.loading = true;
      Apis.chanceFormSave({ ...this.componentProps.params, ...requestParams }).then((data) => {
        doSaveCallBack(data);
        if (data.status == 'success') {
          const parentStore = that.componentProps.parentStore;
          if (typeof (parentStore) === 'undefined') {
            message.success(getLabel(83551, '保存成功！'));
            if (this.componentProps.params.operation == 'add') {
              this.loading = true;
              // 防止创建重复的商机
              setTimeout(() => { window.close(); this.loading = false; }, 1000);
            }
          } else {
            if (parentStore.chanceDialogShow) {
              parentStore.showChanceDialog(false);
            }
            if (parentStore.chanceTabDialogShow) {
              parentStore.showChanceTabDialog(false);
            }
            that.componentWillUnmount();
          }
        } else {
          message.error(`${data.msgcode}!`);
        }
      });
    }

    formFieldChange(valueObj, field) {
      const fieldName = field.domkey[0];
      let newValue = '';
      if (field.conditionType == 'UPLOAD') {
        newValue = valueObj;
      } else {
        newValue = valueObj[fieldName].value;
      }
      // 客户名称联动商机来源
      if (fieldName == 'customerid') {
        const oldCustomerid = this.customerId;
        this.customerId = newValue;
        // 当客户
        if (newValue == '' || (oldCustomerid !== this.customerId)) {
          this.form.updateFields({ comefromid: '' });
          if (this.componentProps.params.operation == 'edit') {
            const comefromid = this.getFieldProps('comefromid');
            // 当商机来源有初始化数据的时候，更换客户将初始化数据清除掉，并保存至数据库【编辑】
            if (comefromid && comefromid.value !== '' && comefromid.value !== '0') {
              this.formFieldBlur('', comefromid);
            }
          }
        }
      }

      // 获取该字段的必填属性等信息
      const obj = this.getFieldProps(fieldName);
      if (obj.conditionType != weaComTypes.INPUT && obj.conditionType != weaComTypes.TEXTAREA) {
        this.formFieldBlur(newValue, field);
      }
    }

    formFieldBlur(v, field) {
      const fieldName = field.domkey[0];
      const p = this.componentProps.params;
      if (p.operation != 'edit') {
        return;
      }
      const oldValue = this.getFieldValueOld(fieldName);
      let newValue;
      // 获取该字段的必填属性等信息
      const obj = this.getFieldProps(fieldName);
      const label = obj.label;
      const viewAttr = obj.viewAttr;
      const conditionType = obj.conditionType;
      const fname = obj.domkey[0];
      if (typeof (v) === 'object') {
        newValue = v[fieldName].value;
      } else {
        newValue = v;
      }
      if (oldValue == newValue) {
        return;
      }
      let checkResult = true;

      if (viewAttr == 3 && newValue == '') {
        this.objTable.refs[fname].showError();
        setTimeout(() => {
          this.form.initFormFields(this.formItemGroups);
        }, 100);
        checkResult = false;
      }
      if (fieldName == 'probability') {
        if (newValue <= 0 || newValue > 1) {
          checkResult = false;
          Modal.warning({
            title: getLabel(15172, '系统提示'),
            content: getLabel(15241, '请输入0～1之间的数'),
            okText: getLabel(33703, '确定'),
          });
          return;
        }
      }
      if (checkResult) {
        const requestParams = {
          sellChanceId: p.sellChanceId,
        };
        requestParams.fieldName = fieldName;
        requestParams.newValue = newValue;
        this.loading = true;
        const that = this;
        Apis.chanceFormUpdate(requestParams).then((data) => {
          that.loading = false;
          if (data.status == 'success') {
            if (conditionType == 'UPLOAD') {
              this.setFieldValueOld(fieldName, newValue, data.datas.attachMentDatas);
            } else {
              this.setFieldValueOld(fieldName, newValue);
            }
            this.getFormData(this.componentInitCallBack);
            message.success(getLabel(83551, '保存成功！'));
          } else {
            message.error(getLabel(83437, '出现错误！') + data.msgcode);
          }
        });
      }
    }

    getRemindInfo = (id) => {
      Apis.getRemindInfo({ customerId: id }).then((data) => {
        if (data.status == 'success') {
          this.remindInfo = data.datas;
        } else {
          message.error(getLabel(83437, '出现错误！') + data.msgcode);
        }
      });
    }

    saveRemindSetting = (params) => {
      Apis_Contact.saveRemindSetting(params).then((data) => {
        if (data.status == 'success') {
          return true;
        }
        message.error(getLabel(83437, '出现错误！') + data.msgcode);
      });
    }

    reDefineField(field) {
      if (field.domkey == 'comefromid' && this.customerId) {
        // 客户名称作为商机来源的参数
        field.browserConditionParam.dataParams.CustomerID = this.customerId;
      }
      return field;
    }

    tableDataChange(datas) {
      // 更新子表状态
      const subTables = this.subTables;
      subTables[0].columnData = datas;
      this.setSubTables(subTables);
      // 汇总预期收益
      let sum = 0;
      if (datas) {
        for (let i = 0; i < datas.length; i++) {
          sum += Number.parseFloat(datas[i].totelprice || 0);
        }
      }
      this.formFieldUpdate('preyield', sum.toFixed(2));
    }
}
